package me.zhengjie.modules.website.controller;

/**
 * 数据统计
 */

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.modules.website.dto.MonthlyStatisticsDto;
import me.zhengjie.modules.website.repository.AccessLogsRepository;
import me.zhengjie.modules.website.repository.ContentTableRepository;
import me.zhengjie.modules.website.repository.FeedbackTableRepository;
import me.zhengjie.modules.website.service.AccessLogsService;
import me.zhengjie.modules.website.service.impl.AccessLogsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/statistics")
@Api(tags = " 网页-统计模块接口")
public class DataStatisticsController {

    @Autowired
    private ContentTableRepository contentTableRepository;

    @Autowired
    private AccessLogsRepository accessLogsRepository;

    @Autowired
    private FeedbackTableRepository feedbackTableRepository;

    @Autowired
    private AccessLogsService accessLogsService;

    @ApiOperation("获取统计数据")
    @GetMapping("/getStats")
    public ResponseEntity<Map<String, Object>> getStatistics() {

        // 统计内容发布数量
        long contentCount = contentTableRepository.count();

        // 统计访问次数 (PV)
        long pageViews = accessLogsRepository.countByPage();

        // 统计访问 IP 数量 (UV)
        long uniqueVisitors = accessLogsRepository.countDistinctIpByPage();

        // 统计建议数量
        long suggestionsCount = feedbackTableRepository.count();

        // 构造返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("CC", contentCount);
        data.put("PV", pageViews);
        data.put("UV", uniqueVisitors);
        data.put("SC", suggestionsCount);

        return ResponseEntity.ok(data);
    }


    @ApiOperation("按月份统计访问量 (PV) 和独立访问人数 (UV)")
    @GetMapping("/monthlyStatistics")
    public ResponseEntity<List<MonthlyStatisticsDto>> getMonthlyStatistics(
            @RequestParam(value = "year", required = false) Integer year) {
        List<MonthlyStatisticsDto> statistics = accessLogsService.getMonthlyStatistics(year);
        return new ResponseEntity<>(statistics, HttpStatus.OK);
    }


    @ApiOperation("查询指定年份各地区访问量和用户数")
    @GetMapping("/by-year")
    public ResponseEntity<List<Object[]>> getVisitStatsForYear(@RequestParam int year) {
        List<Object[]> stats = accessLogsService.getVisitStatsForYear(year);
        return ResponseEntity.ok(stats);
    }
}
